//
//  BaseViewController.m
//  NewiOSProject
//
//  Created by JMMac on 22.12.23.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "BaseViewController.h"
#import "JMLoginVC.h"
#import "JMGlobalHtmlVC.h"

@interface BaseViewController ()<JMPublicAlertViewDelegate>
@property(nonatomic,assign)float scale;
@property (nonatomic,strong)NSMutableDictionary *infoDict;;
@property (nonatomic, strong)UIButton * phoneBtn;//语音验证码弹窗

@end
static NSString *enter = @"Enter";
@implementation BaseViewController
-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSString *vcClass = NSStringFromClass(self.class);
    if ([vcClass isEqualToString:@"JMLoginVC"]) {
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Page" Action:(OUT)];
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([self isKindOfClass:NSClassFromString(@"JMHomeVC")]
       || [self isKindOfClass:NSClassFromString(@"JMMeVC")]
       || [self isKindOfClass:NSClassFromString(@"JMOrderVC")]){
        [self.rdv_tabBarController setTabBarHidden:NO animated:YES];
    }else{
        [self.rdv_tabBarController setTabBarHidden:YES animated:YES];
    }
    if([self isKindOfClass:[JMLoginVC class]] || [self isKindOfClass:[JMGlobalHtmlVC class]]){
        self.floatView.hidden = YES;
    }else{
        self.floatView.hidden = NO;
    }
    NSString *vcClass = NSStringFromClass(self.class);
    if ([vcClass isEqualToString:@"JMLoginVC"]) {
        [JMCommonMethod uploadStatistics:@"Register" actionType:enter parameters:nil];
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Page" Action:(ENTER)];
    }
    if ([vcClass isEqualToString:@"JMProductVC"]) {
        [JMCommonMethod uploadStatistics:@"Products" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMTotalLoanVC"]) {
        [JMCommonMethod uploadStatistics:@"LoanDetails" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMHomeVC"]) {
        [JMCommonMethod uploadStatistics:@"Home" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMCPIListVC"]) {
        [JMCommonMethod uploadStatistics:@"CpiProduct" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMOrderVC"]) {
        [JMCommonMethod uploadStatistics:@"LoanHistory" actionType:enter parameters:nil];
    }
    
    if ([vcClass isEqualToString:@"JMMyFeedbackController"]) {
        [JMCommonMethod uploadStatistics:@"Suggestion" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMServiceController"]) {
        [JMCommonMethod uploadStatistics:@"Complaint" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMChangeMyBankController"]) {
        [JMCommonMethod uploadStatistics:@"EditBankcard" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMSettingsController"]) {
        [JMCommonMethod uploadStatistics:@"Settings" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMMeVC"]) {
        [JMCommonMethod uploadStatistics:@"Mine" actionType:enter parameters:nil];
    }
    if ([vcClass isEqualToString:@"JMBankAccountController"]) {
        [JMCommonMethod uploadStatistics:@"Bankcard" actionType:enter parameters:nil];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [NSMutableArray new];
    self.index = 1;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    self.fd_interactivePopDisabled = NO;
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    self.fd_prefersNavigationBarHidden=YES;
    self.navigationController.navigationBarHidden=YES;

    self.navigationController.navigationBar.hidden = YES;
    
    
    @weakify(self)
    [[NSNotificationCenter defaultCenter]addObserverForName:@"AlertDismiss" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull notification) {
        @strongify(self);
        delayOperation(0.1, ^{
            [_feedbackAlertV removeFromSuperview];
            _feedbackAlertV = nil;
        });
            
    }];
    _scale=1.0;
    if ([[UIScreen mainScreen] bounds].size.height > 480){
        if (kStatusBar_Height() > 20){
            _scale= 667.0/568.0;
        }else {
            _scale = [[UIScreen mainScreen] bounds].size.height / 568.0;
        }
    }
    if([self isKindOfClass:[JMLoginVC class]]){
    }else{
        delayOperation(1, ^{
            [JF_KEY_WINDOW() addSubview:self.floatView];
        });
    }
    self.fd_prefersNavigationBarHidden=YES;
    [self setNavi];
    self.view.backgroundColor = UIColor.whiteColor;
    delayOperation(1.1, ^{
        if(JMProjectManager.sharedJMProjectManager.loginUser.servicePhone.length==0 &&JMProjectManager.sharedJMProjectManager.loginUser.token.length !=0){
            [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/penetrador/amortiguado/equivocariamos") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
                JMProjectManager.sharedJMProjectManager.loginUser.servicePhone = [dataDic safeStringForKey:@"servicePhone"];
                JMProjectManager.sharedJMProjectManager.loginUser.whatsApp = [dataDic safeStringForKey:@"whatsApp"];

                JMProjectManager.sharedJMProjectManager.loginUser.email = [dataDic safeStringForKey:@"email"];

                [self.phoneBtn setTitle:[dataDic safeStringForKey:@"phone"] forState:(UIControlStateNormal)];
                [self.phoneBtn TiaoZhengButtonWithOffsit:5 TextImageSite:(UIButtonTextLeft)];
            } fail:^(NSString * _Nonnull errorMsg) {
                
            }];
        }else{
            [_phoneBtn setTitle:JMProjectManager.sharedJMProjectManager.loginUser.servicePhone forState:(UIControlStateNormal)];
            [self.phoneBtn TiaoZhengButtonWithOffsit:5 TextImageSite:(UIButtonTextLeft)];

        }
    });
}
-(void)backBtnClick{
    if ([self isKindOfClass:[JMGlobalHtmlVC class]] || [self isKindOfClass:[JMWebViewController class]]) {
        [self dismissModalViewControllerAnimated:YES];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSInteger)startTime{
    if(_startTime==0){
        _startTime = (NSInteger)[[NSDate new] timeIntervalSince1970] * 1000;
    }
    return _startTime;
}
-(NSInteger)endTime{
    return  (NSInteger) [[NSDate new] timeIntervalSince1970] * 1000;
}
-(void)setNavi{
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    self.NavImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,self.view.width,NAVIGATION_BAR_HEIGHT())];
    self.NavImg.backgroundColor=[UIColor clearColor];
    self.NavImg.userInteractionEnabled = YES;
    self.NavImg.clipsToBounds = YES;
    [self.view  addSubview:self.NavImg];
    
    self.Navline = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.NavImg.bottom-.5, self.view.width, .5)];
    self.Navline.backgroundColor=mainSepartorColor();
//    [self.NavImg addSubview:_Navline];

    self.scale=1.0;
    if ([[UIScreen mainScreen] bounds].size.height > 480) {
        if (kStatusBar_Height() > 20) {
            self.scale= 667.0/568.0;
        }
        else {
            self.scale = [[UIScreen mainScreen] bounds].size.height / 568.0;
        }
    }
    if (@available(iOS 15.0, *)) {
        [[UITableView appearance] setSectionHeaderTopPadding:0.0f];
    }
        
    
    self.TitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(45*self.scale,kStatusBar_Height(), self.view.width-90*self.scale, 44)];
    self.TitleLabel.textColor = Text_COLOR_LEVEL1();
//    self.TitleLabel.alpha=.7;
    self.TitleLabel.textAlignment = 1;
    self.TitleLabel.font = fontWithWeight(16, UIFontWeightMedium);
    self.TitleLabel.backgroundColor = [UIColor clearColor];
    [self.NavImg addSubview:self.TitleLabel];
    
    self.backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, self.TitleLabel.top, self.TitleLabel.height, self.TitleLabel.height)];
    [self.backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    [self.NavImg addSubview:self.backBtn];
    [self.backBtn setImage:ImageNamed(@"login_back") forState:(UIControlStateNormal)];
    
    self.rightBarBtn = [[UIButton alloc]initWithFrame:(CGRectMake(kAppW()-60,self.backBtn.top, self.TitleLabel.height, self.TitleLabel.height))];
    [self.NavImg addSubview:_rightBarBtn];

}
-(void)PopVC:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)showMessage:(NSString *)message{
    if ([[NSString stringWithFormat:@"%@",message] isEmptyString]) {
        return;
    }
    delayOperation(0, ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:JF_KEY_WINDOW() animated:YES];
        hud.contentColor = WhiteColor();
        hud.bezelView.blurEffectStyle = UIBlurEffectStyleDark;
        hud.label.textColor = WhiteColor();
        hud.mode = MBProgressHUDModeText;
        hud.label.text= message;
        hud.label.font= Font(12);
        hud.removeFromSuperViewOnHide = YES;
        [hud hideAnimated:YES afterDelay:2];
    });
   
}
-(void)showSuccess:(NSString *)message{
   
}

-(void)startAnimating:(NSString *)set{
    
}


-(void)stopAnimating{
   
}
// 生成随机boundary字符串的函数
- (NSString *)generateBoundaryString {
    JMAppConfig *config = JMProjectManager.sharedJMProjectManager.appConfig;
    return [NSString stringWithFormat:@"Boundary-%@", config.uuidString];
}
-(JMFloatIcon *)floatView{
    if(!_floatView){
        _floatView = [JMFloatIcon sharedJMFloatIcon];
        _floatView.frame = CGRectMake(kAppW() - 50, self.view.height - 48-TAB_BAR_HEIGHT(), 48, 48);
        _floatView.userInteractionEnabled = YES;
        [_floatView setImage:ImageNamed(@"service")];
        @weakify(self)
        [_floatView tapAction:^(UIView *sender) {
            @strongify(self);
            [self.feedbackAlertV show];
        }];
    }
    return _floatView;
}

- (void)didClickBtnAtIndex:(NSInteger)index withButton:(JMLoadingButton *)sender{
    [self startAnimating:nil];
    if(self.textV.textView.text.length==0){
        return;
    }
    NSDictionary *para = @{
        @"arregostado" : self.TitleLabel.text?:@"",
        @"orlemos": @{@"info":self.infoDict,@"content":self.textV.textView.text?:@""}.jsonStringEncoded

    };
    @weakify(self)
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/penetrador/insuflabais/escachifollais") params:para success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopAnimating];
            [self.feedbackAlertV.firstBtn endLoading];
            [self.feedbackAlertV dismiss];
            [self showSuccess:@"Enviado con éxito"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        } fail:^(NSString * _Nonnull errorMsg) {
            [self stopAnimating];
        }];
}
///api/user/complaint
-(JMPublicAlertView *)feedbackAlertV{
    if(!_feedbackAlertV){
        _feedbackAlertV = [[JMPublicAlertView alloc]initWithFrame:(CGRectMake(0, 0, kAppW()-48, 480))
                                                           andTitle:@"Retroalimentación"
                                                           subTitle: @"Describe el problema relacionado encontrado"
                                                         BottomBtns:@[@"Entregar"]
                                                           Position:JMPublicAlertViewPositionCenter
                                                       btnDirection:JMPublicAlertViewButtonDirectionVer];
        _feedbackAlertV.delegate = self;
        _feedbackAlertV.firstBtn.bottom = _feedbackAlertV.height-137;
        _feedbackAlertV.firstBtn.enable = NO;
        _feedbackAlertV.firstBtn.width = _feedbackAlertV.width-56;
        _feedbackAlertV.firstBtn.height = 52;
        
        
//        _feedbackAlertV.subTitleLab.font = fontWithWeight(12, UIFontWeightMedium);
        _textV = [[BRPlaceholderTextView alloc]initWithFrame:(CGRectMake(24, _feedbackAlertV.firstBtn.top-170, _feedbackAlertV.width-48, 150))];
        [_feedbackAlertV addSubview:_textV];
        _textV.backgroundColor = Hex_Str_COLOR(@"#F6F9FE");
        _textV.cornerRadius =10;
        _textV.placeholder = @"Por favor inserte";
        
        @weakify(self);
        [_textV addTextViewChangeEvent:^(BRPlaceholderTextView *text) {
            @strongify(self);
            if (text.textView.text.length) {
                _feedbackAlertV.firstBtn.enable = YES;
            }else{
                _feedbackAlertV.firstBtn.enable = NO;
            }
        }];
        
        UILabel *tipsLab = [JMControl createLabelWithFrame:(CGRectMake(20, _feedbackAlertV.firstBtn.bottom+10, _feedbackAlertV.firstBtn.width, fontWithWeight(12, UIFontWeightMedium).lineHeight*2+2)) Font:fontWithWeight(12, UIFontWeightRegular) Text:@"Usted también puede llamar a la atención al cliente directamente:" color:Hex_Str_COLOR(@"#555555")];
        [_feedbackAlertV addSubview:tipsLab];
        
        
        
        _phoneBtn = [JMControl createLoadingButtonWithFrame:(CGRectMake(28, _feedbackAlertV.height-24-56, 155, 52)) Target:self Action:@selector(copyBtnClick) Title:JMProjectManager.sharedJMProjectManager.loginUser.servicePhone titlColor:Text_COLOR_LEVEL1() font:Font(14) tag:1 backgroundColor:UIColor.clearColor];
        [_feedbackAlertV addSubview:_phoneBtn];
        [JMControl addHorLineWithSpace:0 top:_phoneBtn.height height:1 bgColor:mainSepartorColor() toView:_phoneBtn];
        
        UIButton *copyBtn = [JMControl createButtonWithFrame:(CGRectMake(_feedbackAlertV.width-25-82, _phoneBtn.top, 82, _phoneBtn.height)) title:@"Copy" titleColor:mainSchemeColor() titleFont:Font(16) backgroundColor:UIColor.clearColor Target:self Action:@selector(copyBtnClick)];
        [_feedbackAlertV addSubview:copyBtn];

    }
    return _feedbackAlertV;
}
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];
    if(sender.text.length){
        self.feedbackAlertV.firstBtn.enable = YES;
    }else{
        self.feedbackAlertV.firstBtn.enable = NO;
    }
}
-(void)copyBtnClick{
    UIPasteboard *past = [UIPasteboard generalPasteboard];
    past.string = JMProjectManager.sharedJMProjectManager.loginUser.servicePhone;
    [self showMessage:@"éxito"];
}
-(UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), 60))];
        UIButton *agreementBtn = [JMControl createButtonWithFrame:(CGRectMake(0, 0, kAppW(), 60)) title:@"《Política de privacidad》" titleColor:Hex_Str_COLOR(@"#222222") titleFont:Font(15) backgroundColor:UIColor.clearColor Target:self Action:@selector(agreementBtnClick)];
        [_footerView addSubview:agreementBtn];
    }
    return _footerView;
}
-(void)agreementBtnClick{
    
}

-(void)openCreditUrl:(NSString *)type{
    if (type.intValue==1) {
        [JMCommonMethod openFico];
    }
    if (type.intValue==2) {
        [JMCommonMethod openCloudun];
    }
    if (type.intValue==3) {
        [JMCommonMethod openFAQ];
    }
}

@end
